import * as React from 'react';
import { Card } from 'antd';
import { api } from '../../../common/api';
const { useState, useEffect } = React;
import InfoCard from '../../../component/info-card';
import Chart from '../../../component/chart';
import { collectRequestTimes } from '../utils';
import { distributionLevels } from '../../../component/speed-data-overview';
import { barChartTemplate } from '../../../component/analysisPanel/template';
import { calcCityDistributionSeriseData } from '../../static-speed/calc';

import './hover.less';

interface HoverProps {
    startDate: number,
    endDate: number,
    url: string,
    projectId: number
}

export default function Hover(props: HoverProps) {
    const { url, startDate, endDate, projectId } = props;
    const [loading, setLoading] = useState(true);
    const [successRate, setSuccessRate] = useState(0);
    const [distributionSeries, setDistributionSeries] = useState([]);

    useEffect(() => {
        setLoading(true);
        async function fetchData() {
            const data = await api({
                method: 'GET',
                url: `speed-server/${projectId}/cgi-specific`,
                params: {
                    startDate,
                    endDate,
                    url: encodeURIComponent(url)
                }
            }) as any;
            const [successTimes, tempSuccessRate] = collectRequestTimes(data.status);
            setDistributionSeries(calcCityDistributionSeriseData(data.distribution));
            setSuccessRate(tempSuccessRate);
            setLoading(false);
        }
        fetchData();

    }, [url, startDate, endDate])
    return <div className="hover">
        <InfoCard bordered={true} loading={loading} title='当日请求成功率(%)' num={successRate * 100}></InfoCard>
        <Card
            bordered={false}
            hoverable
            style={{
                minWidth: 500,
                width: 'fit-content',
                marginRight: 50,
                minHeight: 280
            }}
            bodyStyle={{
                padding: 0
            }}
            loading={loading}
        >
            <Chart styleName='distribution-chart' option={barChartTemplate(`当日请求速度分布`, distributionSeries, distributionLevels)}></Chart>
        </Card>
    </div>
}